package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.alibaba.druid.util.StringUtils;
import com.ruoyi.system.domain.GoodsFl;
import com.ruoyi.system.domain.GoodsList;
import com.ruoyi.system.domain.InfiniteGoods;
import com.ruoyi.system.mapper.GoodsFlMapper;
import com.ruoyi.system.mapper.GoodsListMapper;
import com.ruoyi.system.mapper.GoodsMapper;
import com.ruoyi.system.mapper.InfiniteGoodsMapper;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Goods;
import com.ruoyi.system.service.IGoodsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 盒子信息Controller
 * 
 * @author ruoyi
 * @date 2022-05-24
 */
@RestController
@RequestMapping("/system/goods")
public class GoodsController extends BaseController
{
    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsFlMapper goodsFlMapper;


    @Resource
    private GoodsListMapper goodsListMapper;

    @Resource
    private InfiniteGoodsMapper infiniteGoodsMapper;





    @PostMapping("/userMadeList")
    public AjaxResult userMadeList()
    {


        return AjaxResult.success();
    }


    @PostMapping("/copyGoods")
    public AjaxResult copyGoods(@RequestParam("goodsId")Integer goodsId
    ,@RequestParam("type")Integer type)
    {
        if(type==1)
        {
            Goods goods = goodsMapper.selectGoodsById(goodsId);
            if(goods == null)
            {
                return AjaxResult.error("当前盒子ID对应盒子不存在,id 是["+goodsId+"]");

            }
            //创建一级盒子 并得到该盒子的Id
            int insert = goodsMapper.insertGoods(goods);

            int newGoodsId =goods.getId();// 插入之后返回的新Id

            logger.info("新的盒子Id是： {}",newGoodsId);


            //找出goods下所有的 goodsList
            List<GoodsList> list =goodsListMapper.
                    selectGoodsListByGoodsIdAndGoodType(goodsId,1);

            list.forEach(
                    l->{
                        logger.info("commonId:{}",l.getCommonId());
                        l.setGoodsId(newGoodsId);
                        l.setSaleNum(0L);

                        goodsListMapper.insertGoodsList(l);
                    }

            );
        }else if(type==2)
        {

            InfiniteGoods infiniteGoods = infiniteGoodsMapper.selectInfiniteGoodsById(goodsId);
            if(infiniteGoods!=null)
            {
                infiniteGoods.setProfit(new BigDecimal(0));
                infiniteGoods.setHotkey(0);
                infiniteGoodsMapper.insertInfiniteGoods(infiniteGoods);
                Integer newId = infiniteGoods.getId();
                //找出goods下所有的 goodsList
                List<GoodsList> list =goodsListMapper.
                        selectGoodsListByGoodsIdAndGoodType(goodsId,2);

                list.forEach(
                        l->{
                            l.setGoodsId(newId);
                            goodsListMapper.insertGoodsList(l);
                        }

                );

            }


        }


        return AjaxResult.success("一键复制成功~");
    }


    @PostMapping("/connect")
    public AjaxResult connect(@RequestParam("goodsId")Integer goodsId,
    @RequestParam("topId")Integer topId,@RequestParam("id")Integer id
    )
    {
       int insert  = goodsFlMapper.insertConnect(goodsId,topId,id);

        return AjaxResult.success("关联成功");
    }


    @PostMapping("/searchGoodsId")//查看当前二级分类下关联的goodsId
    public AjaxResult searchGoodsIds(@Param("topId")Integer topId,@Param("fid")Integer fid)
    {
        List<Goods> list =goodsFlMapper.selectConnect(topId,fid);

        return AjaxResult.success(list);
    }

    @PostMapping("/deleteConnect")
    public AjaxResult deleteConnect(@RequestParam("goodsId")Integer goodsId,
                                    @RequestParam("topId")Integer topId,@RequestParam("id")Integer id)
    {
        int delete = goodsFlMapper.deleteConnect(goodsId,topId,id);
        logger.info("delete: "+delete);

        return AjaxResult.success("解除关联成功");
    }


    @PostMapping("/oneAndTwoFl")
    public AjaxResult oneAndTwo()
    {

      List<GoodsFl> one = goodsFlMapper.selectOneList();
        for (GoodsFl goodsFl : one) {
            List<GoodsFl> two =goodsFlMapper.selectTwoList(goodsFl.getId());
            goodsFl.setTwos(two);

        }

        return AjaxResult.success(one);
    }

    @PostMapping("/deleteFlById")
    public AjaxResult deleteById(@RequestParam("ids")Integer[] id)
    {

        int i = goodsFlMapper.deleteGoodsFlByIds(id);

        return AjaxResult.success("删除成功");
    }

    @PostMapping("/addFl")
    public AjaxResult add(@RequestBody GoodsFl goodsFl)
    {
        int i = goodsFlMapper.insertGoodsFl(goodsFl);

        return AjaxResult.success("添加分类成功");
    }

    @PostMapping("/editFl")
    public AjaxResult edit(@RequestBody GoodsFl goodsFl)
    {
        int i = goodsFlMapper.updateGoodsFl(goodsFl);

        return AjaxResult.success("更新成功");
    }



    @PostMapping("/qualifying")
    public AjaxResult qualifying(@RequestParam("goodsId") Integer goodsId)
    {
        if(goodsMapper.checkQualifying(goodsId)!=0)
        {
            return AjaxResult.error("你已添加排位！");
        }


        Goods goods = goodsService.selectGoodsById(goodsId);
        Integer allIndex = goodsMapper.selectCountRemain(goodsId,1);
        Integer[] size = new Integer[allIndex];
        for (int i = 0; i < size.length; i++) {
            size[i]=i+1;
        }
        for (Integer i = 1; i <= goods.getStock(); i++) {
           int insert  =  goodsMapper.insertQualifying(goodsId,i,size);
           logger.info("插入中赏记录条数，{}",insert);
        }


        return AjaxResult.success();
    }

    /**
     * 查询盒子信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(Goods goods)
    {
        startPage();
        List<Goods> list = goodsService.selectGoodsList(goods);
        return getDataTable(list);
    }

    /**
     * 导出盒子信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:goods:export')")
    @Log(title = "盒子信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Goods goods)
    {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        util.exportExcel(response, list, "盒子信息数据");
    }

    /**
     * 获取盒子信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(goodsService.selectGoodsById(id));
    }

    /**
     * 新增盒子信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:add')")
    @Log(title = "盒子信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Goods goods)
    {
        int goodsId = goodsService.insertGoods(goods);
        return AjaxResult.success("新增盒子成功！");
    }

    /**
     * 修改盒子信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:edit')")
    @Log(title = "盒子信息", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody Goods goods)
    {

        return toAjax(goodsService.updateGoods(goods));
    }

    /**
     * 删除盒子信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:remove')")
    @Log(title = "盒子信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(goodsService.deleteGoodsByIds(ids));
    }
}
